import asyncio
import threading
import time


def my_sleep(n):
    print(f"enter sleep, tid: {threading.get_ident()}")
    time.sleep(n)


async def play(init_event: asyncio.Event):
    await init_event.wait()
    print(f"enter play, tid: {threading.get_ident()}")
    for _ in range(5):
        # await asyncio.sleep(1)  # 5 second, 在当前线程中执行函数
        # time.sleep(1) # 25 seconds
        await asyncio.to_thread(
            my_sleep, 1
        )  #  0.5 second， 在新的线程中执行函数，当前线程等待新线程完成任务
        for _ in range(1000):
            pass
    print("exit play")


async def main():
    start = time.time()
    tasks = []
    init_event = asyncio.Event()
    for _ in range(5):
        tasks.append(asyncio.create_task(play(init_event)))
    await asyncio.sleep(1)
    print("Init Done")
    # 确保初始化完成
    init_event.set()
    await asyncio.gather(*tasks)
    print(f"total time: {time.time() - start} seconds")


if __name__ == "__main__":
    asyncio.run(main())
